package cn.xuyun.cc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.xuyun.cc.tcp.bean.CommandInfo;
import cn.xuyun.cc.tcp.bean.CommandReq;
import cn.xuyun.cc.tcp.service.MongoService;

/**
 * Servlet implementation class GetCmdDetailServlet
 */
@WebServlet("/st/GetCmdDetail")
public class GetCmdDetailServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 * 
	 *      <detail> <device >/////设备ID、命令开始时间、命令执行结果（等待、执行、完成，超时）； <uid></uid>
	 *      -- 设备id <begintime></begintime> --命令开始时间 2012-10-29 10:00:01
	 *      <result></result> 0/1/2/3, 0表示执行完成, 1表示等待执行，2正在执行，3超时
	 *      <content></content> 设备返回的内容 </device>
	 * 
	 * 
	 *      <device >/////设备ID、命令开始时间、命令执行结果（等待、执行、完成，超时）； <uid></uid> -- 设备id
	 *      <begintime></begintime> --命令开始时间 2012-10-29 10:00:01
	 *      <result></result> 0/1/2/3, 0表示执行完成, 1表示等待执行，2正在执行，3超时
	 *      <content></content> 设备返回的内容 </device>
	 * 
	 *      …… </detail>
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String key = request.getParameter("key");
		String user = request.getParameter("user");

		CommandReq cr = MongoService.getCmdreq(key);

		SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		StringBuilder sb=new StringBuilder();
		sb.append("<detail>");
		long curtime=System.currentTimeMillis();
		if (cr != null) {

			for (String uid : cr.getDevice_id()) {
				
				sb.append("<device>");
				sb.append("<uid>"+uid+"</uid>");
				sb.append("<begintime>"+sdf.format(new Date(cr.getBegin_time()))+"</begintime>");
				CommandInfo ci=MongoService.getResponse(key, uid);
				if(ci!=null)
				{
					sb.append("<result>0</result>");
					sb.append("<content>"+new String(ci.getResponse())+"</content>");
				}else if((curtime-cr.getBegin_time())/1000>cr.getTimeout())
				{
					sb.append("<result>3</result>");
					sb.append("<content></content>");
				}else{
					sb.append("<result>1</result>");
					sb.append("<content></content>");
				}
				sb.append("</device>");
			}
		}
		sb.append("</detail>");

	}

}
